/**
 * 
 */
package com.mango.mstock.support.utils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.time.DateUtils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.widget.ListView;
import android.widget.Toast;

import com.mango.common.model.Security;
import com.mango.common.util.CommonUtil;
import com.mango.common.util.DateUtil;
import com.mango.mstock.ListViewAdapter;
import com.mango.mstock.MainActivity;
import com.mango.mstock.R;
import com.mango.mstock.model.MyFavorite;
import com.mango.mstock.support.MStockGlobalVars;
import com.mango.mstock.support.db.DBManager;

/**
 * @author mango
 *
 */
public class MStockUtil {
	
    public static int getColorByLatestPrice(float yesterdayprice, float latestprice) {
    	if (latestprice == yesterdayprice) {
    		return Color.GRAY;
    	} else if (latestprice > yesterdayprice) {
    		return Color.RED;
    	} else {
    		return Color.GREEN;
    	}
    }
    
    /*
     * get latest MyFavorite from sinajs in transaction time,
     * or from sqlite in other time. 
     * 
     */
    public static Security getLatestMyFavorite(String code) {
    	MyFavorite favorite = null;
    	if (!CommonUtil.isTransactionTime(Calendar.getInstance())) {
    		// treat latest price as yesterday price.
    		DBManager dbManager = new DBManager();
    		favorite = dbManager.findByCode(code);
    		dbManager.closeDB();
    		
			if (favorite == null) {
				Security security = findandSaveSecurityFromSinaJS(code);
				favorite = convert2MyFavorite(security);
			} else {
				Date lastrecordtime = DateUtil.toDate(favorite.getUpdatedate(), DateUtil.DATE_TIME_FORMAT);
	    		if (!DateUtils.isSameDay(new Date(), lastrecordtime) ||
	    				CommonUtil.isTransactionTime(lastrecordtime)) {
	    			// last record time is not today, or not in transaction time, 
	    			// we do not ensure it is the latest price.
	    			Security security = findandSaveSecurityFromSinaJS(code);
	    			favorite = convert2MyFavorite(security);
	    		}
			}
		} else {
			Security security = findandSaveSecurityFromSinaJS(code);
			favorite = convert2MyFavorite(security);
		}
    	
    	return favorite;
    }
    
    private static Security findandSaveSecurityFromSinaJS(String code) {
		Security security = CommonUtil.getSecurityFromSinaJS(code);
		// store them in file because we need it next time when app started.
//		MStockPreference.getInstance().put(code + "_latestprice", stock.getLatestPrice());
//		MStockPreference.getInstance().put(code + "_yesterdayprice", stock.getYesterdayPrice());
		DBManager dbManager = new DBManager();
		dbManager.saveOrUpdate(convert2MyFavorite(security));
		dbManager.closeDB();
		
		return security;
    }
    
    @SuppressLint("InflateParams")
	public static void saveMyFavorite(final String code) {
    	final DBManager dBManager = new DBManager();
    	MyFavorite favorite = dBManager.findByCode(code);
    	dBManager.closeDB();
    	
    	
    	if (favorite == null) {
    		Thread thread = new Thread(new Runnable() {
    			@Override
    			public void run() {
    				findandSaveSecurityFromSinaJS(code);
    			}
    		});
    		thread.start();
    		
    		while (thread.isAlive()) {
        		// wait until thread ends.
        	}
        	Context context = MStockGlobalVars.getCurrentContext();
        	if (context instanceof MainActivity) {
        		MainActivity activity = (MainActivity) context;
        		ListView listView = (ListView) activity.findViewById(R.id.list_items);
        		ListViewAdapter adapter = (ListViewAdapter) listView.getAdapter();
        		adapter.addItem(convert2Map(new DBManager().findByCode(code)));
        	}
    	} else {
    		Toast.makeText(MStockGlobalVars.getCurrentContext(), 
    				"You have already has added this stock.", Toast.LENGTH_SHORT).show();
    	}
    	
	}
    
    public static MyFavorite convert2MyFavorite(Security security) {
    	if (security == null) return null;
    	MyFavorite result = new MyFavorite();
    	result.setCode(security.getCode());
    	result.setName(security.getName());
    	result.setYesterdayPrice(security.getYesterdayPrice());
    	result.setLatestPrice(security.getLatestPrice());
    	return result;
    }
    
    public static Map<String, Object> convert2Map(MyFavorite favorite) {
    	Map<String, Object> item = new HashMap<String, Object>();
    	item.put("code", favorite.getCode());
    	item.put("name", favorite.getName());
    	item.put("yesterdayprice", favorite.getYesterdayPrice());
    	item.put("latestprice", favorite.getLatestPrice());
    	item.put("updatedate", favorite.getUpdatedate());
    	return item;
    }
    
	/**  
     * Initialize information of favorite items  
     */  
    public static List<Map<String, Object>> getMyFavoriteItems() {   
        List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();   
        
        for (MyFavorite favorite : getAllMyFavors()) {
        	Map<String, Object> map = new HashMap<String, Object>();    
            map.put("code", favorite.getCode());  
            map.put("name", favorite.getName()); 
            map.put("latestprice", favorite.getLatestPrice());  
            map.put("yesterdayprice", favorite.getYesterdayPrice());
            map.put("updatedate", favorite.getUpdatedate());
            listItems.add(map); 
        }
        
        return listItems;   
    } 
    
    private static List<MyFavorite> getAllMyFavors() {
    	DBManager dbManager = new DBManager();
    	List<MyFavorite> allMyFavors = dbManager.findAll();
        dbManager.closeDB();
        
    	return allMyFavors;
    } 
    
}
